<template>
	<view class="container">
		<!-- 预约停车头部区域 -->
		<view class="header-section">
			<image class="header-bg-image" src="/static/banner.jpg" mode="aspectFill" @error="handleBannerError">
			</image>
		</view>

		<!-- 机场停车和高铁站停车按钮 -->
		<view class="service-buttons">
			<view class="service-button airport-button" @click="handleAirportParking">
				<view class="button-icon">✈️</view>
				<text class="button-text">机场停车</text>
			</view>
			<view class="service-button railway-button" @click="handleRailwayParking">
				<view class="button-icon">🚄</view>
				<text class="button-text">高铁站停车</text>
			</view>
		</view>

		<!-- 车位预约保障 -->
		<view class="guarantee-section">
			<view class="guarantee-title">
				<text class="guarantee-icon">▶</text>
				<text class="guarantee-text">车位预约保障</text>
				<text class="guarantee-icon">◀</text>
			</view>
			<view class="guarantee-items">
				<view class="guarantee-item">
					<view class="guarantee-item-icon">🏷️</view>
					<text class="guarantee-item-text">享团购价</text>
					<text class="guarantee-item-desc">一单也是拼团价</text>
				</view>
				<view class="guarantee-item">
					<view class="guarantee-item-icon">🚗</view>
					<text class="guarantee-item-text">免费接送</text>
					<text class="guarantee-item-desc">提供往返摆渡车</text>
				</view>
				<view class="guarantee-item">
					<view class="guarantee-item-icon">🚐</view>
					<text class="guarantee-item-text">预订有位</text>
					<text class="guarantee-item-desc">下单保障车位</text>
				</view>
			</view>
		</view>

		<!-- 热门机场/高铁站列表 -->
		<view class="popular-section">
			<view class="section-header">
				<text class="section-icon">🔥</text>
				<text class="section-title">热门机场/高铁站</text>
				<text class="section-more" @click="navigateToList">更多 ></text>
			</view>

			<view class="popular-grid">
				<view class="popular-item" v-for="(station, index) in popularStations" :key="index"
					@click="handleStationClick(station)">
					<image class="station-image" :src="station.image" mode="aspectFill" @error="handleImageError">
					</image>
					<view class="station-info">
						<text class="station-name">{{ station.name }}</text>
						<text class="station-price">低至{{ station.price }}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'
import { getPopularParkingLots } from '../../api/parking.js'
import { getFullImageUrl } from '../../utils/request.js'

// 响应式数据
const popularStations = ref([])

const loading = ref(false)

// 获取热门机场/高铁站数据
const loadPopularStations = async () => {
	if (loading.value) return

	loading.value = true
	try {
		// 调用API获取热门机场/高铁站数据
		const response = await getPopularParkingLots({
			limit: 4,
			type: 'all' // 获取所有类型，包括机场和高铁站
		})

		if (response.success && response.data && response.data.length > 0) {
			// 处理返回的数据，转换为前端需要的格式
			popularStations.value = response.data.map(station => ({
				id: station.id,
				name: station.name,
				price: formatHomePrice(station.price_rules),
				image: getStationImage(station),
				type: getStationType(station.name, station.address),
				order_count: station.order_count || 0,
				address: station.address
			}))

			console.log('热门机场/高铁站数据已加载:', popularStations.value)
		} else {
			console.warn('获取热门机场/高铁站数据为空')
			popularStations.value = []
		}
	} catch (error) {
		console.error('获取热门机场/高铁站失败:', error)
		uni.showToast({
			title: '获取数据失败',
			icon: 'none',
			duration: 2000
		})
	} finally {
		loading.value = false
	}
}

// 机场停车处理
const handleAirportParking = () => {
	uni.navigateTo({
		url: '/pages/category-select/category-select?type=airport'
	})
}

// 高铁站停车处理
const handleRailwayParking = () => {
	uni.navigateTo({
		url: '/pages/category-select/category-select?type=railway'
	})
}

// 机场/高铁站点击处理
const handleStationClick = (station: any) => {
	uni.navigateTo({
		url: `/pages/detail/detail?id=${station.id}&type=${station.type}`
	})
}

// 跳转到列表页
const navigateToList = () => {
	uni.switchTab({
		url: '/pages/list/list'
	})
}

// 处理图片加载错误
const handleImageError = (e: any) => {
	console.log('图片加载失败:', e)
	// 可以设置默认图片
	e.target.src = '/static/parking-default.svg'
}

// 处理banner图片加载错误
const handleBannerError = (e: any) => {
	console.log('Banner图片加载失败:', e)
	// 可以隐藏图片或设置默认背景色
}

// 规范化价格规则（兼容字符串/对象）
const normalizePriceRules = (rules: any) => {
	if (!rules) return null
	if (typeof rules === 'string') {
		try { return JSON.parse(rules) } catch { return null }
	}
	if (typeof rules === 'object') return rules
	return null
}

// 首页价格展示（返回完整文本，使用7天均价逻辑与列表页保持一致）
const formatHomePrice = (priceRules: any) => {
	const rules = normalizePriceRules(priceRules)
	if (!rules) return '面议'

	// 累计天数收费（含室内外分别定价）- 使用7天均价（支持24小时计费和自然天计费）
	if (rules.type === 'cumulative_daily' || rules.type === 'rolling_24h' || rules.daily_prices) {
		// 室内外分别定价：用第7天累计价/7，取最小均价
		if (rules.indoor_outdoor_enabled && rules.indoor_prices && rules.outdoor_prices) {
			const indoorPrices = rules.indoor_prices.daily_prices
			const outdoorPrices = rules.outdoor_prices.daily_prices
			if (indoorPrices && outdoorPrices) {
				const indoorDay7 = Number(indoorPrices.day_7 || 0)
				const outdoorDay7 = Number(outdoorPrices.day_7 || 0)
				const avgs = [indoorDay7, outdoorDay7].filter(v => v > 0).map(v => v / 7)
				if (avgs.length === 0) return '面议'
				const minAvg = Math.min(...avgs)
				return `¥${Math.round(minAvg)}/天`
			}
		}
		// 统一定价（取第7天累计价/7）
		const dailyPrices = rules.daily_prices
		if (dailyPrices) {
			const day7Price = Number(dailyPrices.day_7 || 0)
			if (day7Price <= 0) return '面议'
			return `¥${Math.round(day7Price / 7)}/天`
		}
	}

	// 旧的小时价数组：估算为每天价格
	if (Array.isArray(rules) && rules.length > 0) {
		const minHour = Math.min(...rules.map((r: any) => Number(r.price_per_hour) || 0))
		return `¥${Number(minHour * 24).toFixed(2)}/天`
	}

	return '面议'
}

// 获取停车场图片
const getStationImage = (station: any) => {
	// 如果有图片URL，使用第一张
	if (station.image_urls && Array.isArray(station.image_urls) && station.image_urls.length > 0) {
		return getFullImageUrl(station.image_urls[0])
	}

	// 根据名称返回对应的默认图片
	const name = station.name || ''
	if (name.includes('浦东')) return '/static/stations/pudong-airport.svg'
	if (name.includes('大兴')) return '/static/stations/daxing-airport.svg'
	if (name.includes('萧山')) return '/static/stations/xiaoshan-airport.svg'
	if (name.includes('咸阳')) return '/static/stations/xianyang-airport.svg'

	// 默认图片
	return '/static/stations/pudong-airport.svg'
}

// 判断停车场类型
const getStationType = (name: string, address: string) => {
	const fullText = (name + address).toLowerCase()
	if (fullText.includes('机场') || fullText.includes('航站')) {
		return 'airport'
	}
	if (fullText.includes('高铁') || fullText.includes('火车站') || fullText.includes('站')) {
		return 'railway'
	}
	return 'airport' // 默认为机场
}





// 下拉刷新
const handleRefresh = async () => {
	await loadPopularStations()
	uni.stopPullDownRefresh()
}

// 生命周期
onMounted(() => {
	console.log('首页加载完成')
	loadPopularStations()
})

// 下拉刷新
onPullDownRefresh(() => {
	handleRefresh()
})
</script>

<style scoped>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
}

/* 头部预约停车区域样式 */
.header-section {
	height: 300rpx;
	position: relative;
	overflow: hidden;
}

.header-bg-image {
	width: 100%;
	height: 100%;
	position: absolute;
	top: 0;
	left: 0;
	z-index: 1;
}







/* 服务按钮样式 */
.service-buttons {
	display: flex;
	gap: 20rpx;
	margin: 30rpx 20rpx;
}

.service-button {
	flex: 1;
	height: 200rpx;
	border-radius: 20rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	color: white;
	font-weight: bold;
	position: relative;
	overflow: hidden;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
	transition: all 0.3s ease;
	transform: translateY(0);
}

.service-button:active {
	transform: translateY(4rpx);
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
}

.airport-button {
	background: linear-gradient(135deg, #32A3FF 0%, #1E88E5 100%);
}

.railway-button {
	background: linear-gradient(135deg, #FF6B35 0%, #F4511E 100%);
}

.button-icon {
	font-size: 60rpx;
	margin-bottom: 15rpx;
}

.button-text {
	font-size: 32rpx;
	font-weight: 600;
}

/* 车位预约保障样式 */
.guarantee-section {
	background: white;
	margin: 20rpx;
	border-radius: 20rpx;
	padding: 30rpx 20rpx;
}

.guarantee-title {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 30rpx;
	gap: 10rpx;
}

.guarantee-icon {
	font-size: 24rpx;
	color: #32A3FF;
}

.guarantee-text {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.guarantee-items {
	display: flex;
	justify-content: space-between;
}

.guarantee-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;
}

.guarantee-item-icon {
	font-size: 50rpx;
	margin-bottom: 15rpx;
}

.guarantee-item-text {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 8rpx;
}

.guarantee-item-desc {
	font-size: 22rpx;
	color: #666;
}

/* 热门机场/高铁站样式 */
.popular-section {
	margin: 20rpx;
}

.section-header {
	display: flex;
	align-items: center;
	padding: 0 20rpx 20rpx;
	gap: 10rpx;
}

.section-icon {
	font-size: 28rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	flex: 1;
}

.section-more {
	font-size: 28rpx;
	color: #32A3FF;
}

.popular-grid {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 20rpx;
}

.popular-item {
	background: white;
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
	transform: translateY(0);
}

.popular-item:active {
	transform: translateY(-4rpx);
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
}

.station-image {
	width: 100%;
	height: 200rpx;
}

.station-info {
	padding: 20rpx;
}

.station-name {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 8rpx;
	display: block;
}

.station-price {
	font-size: 24rpx;
	color: #FF6B35;
	font-weight: 500;
}
</style>
